package first.codeTop.byteDance;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName Leetcode103
 * @description:
 * @author: 荣燊
 * @create: 2021-07-24 14:46
 **/
public class Leetcode103 {
    // 二叉树的锯齿形层序遍历,就是二叉树的之字打印
    public static void main(String[] args) {

    }

    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();
        if (root == null) {
            return res;
        } else {
            deque.add(root);
        }


        while (!deque.isEmpty()) {
            Deque<Integer> list = new LinkedList<>();
            for (int i=deque.size(); i>0; i--) {
                TreeNode node = deque.poll();
                if (res.size() % 2 == 0) {
                    list.addFirst(node.val);
                } else {
                    list.addLast(node.val);
                }

                if (node.left != null) {
                    deque.add(node.left);
                }
                if (node.right != null) {
                    deque.add(node.right);
                }
            }
            // 取出list中的数据
            List<Integer> list1 = new ArrayList<>();
            while (!list.isEmpty()) {
                list1.add(list.pollLast());
            }
            res.add(list1);
        }
        return res;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
